import findExec from 'find-exec'
import { spawn } from 'child_process'
var players = [
    'mplayer',
    'afplay',
    'mpg123',
    'mpg321',
    'play',
    'omxplayer',
    'aplay',
    'cmdmp3',
    'cvlc',
    'powershell'
]

export class AudioPlayer {
    constructor(opts) {
        opts = opts || {}
        this.players = opts.players || players
        this.player = opts.player || findExec(this.players)
    }

    play(what, options, next) {
        next = next || function () { }
        next = typeof options === 'function' ? options : next
        options = typeof options === 'object' ? options : {}
        options.stdio = 'ignore'

        return new Promise((resolve, reject) => {
            if (!what) {
                reject(new Error("No audio file specified"));
            }

            if (!this.player) {
                reject(new Error("Couldn't find a suitable audio player"));
            }

            var args = Array.isArray(options[this.player]) ? options[this.player].concat(what) : [what]
            var process = spawn(this.player, args, options)
            if (!process) {
                reject(new Error("Unable to spawn process with " + this.player));
            }
            process.on('close', function (err) { resolve(err && !err.killed ? err : null) });
        });
    }
}
